<?php
// +----------------------------------------------------------------------
//公共函数文件
// +----------------------------------------------------------------------
use app\admin\model\Node as NodeModal;
use think\Config;
use think\Db;
use Wechat\Loader;
use Wechat\WechatReceive;

use Rong\Api;

use think\Loader as Load;

/**
 * 打印输出数据到文件
 * @param mixed $data
 * @param bool $replace
 * @param string|null $pathname
 */
function p($data, $replace = false, $pathname = NULL)
{
    is_null($pathname) && $pathname = RUNTIME_PATH . date('Ymd') . '.txt';
    $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, TRUE) : var_export($data, TRUE)) . "\n";
    $replace ? file_put_contents($pathname, $str) : file_put_contents($pathname, $str, FILE_APPEND);
}

/**
 * 获取微信操作对象
 * @param string $type
 * @return WechatReceive
 */
function & load_wechat($type = '')
{
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        $config = Config::get('wechat');
        $config['cachepath'] = CACHE_PATH . 'wechat' . DS;
        $wechat[$index] = &Loader::get($type, $config);
    }
    return $wechat[$index];
}

/**
 * 安全URL编码
 * @param array $data
 * @return string
 */
function encode($data)
{
    return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(serialize($data)));
}

/**
 * 安全URL解码
 * @param string $string
 * @return string
 */
function decode($string)
{
    $data = str_replace(['-', '_'], ['+', '/'], $string);
    $mod4 = strlen($data) % 4;
    !!$mod4 && $data .= substr('====', $mod4);
    return unserialize(base64_decode($data));
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeModal::checkAuthNode($node);
}

/**
 * 从配置表读取配置信息
 * @param string $name
 * @return string
 */
function sysconf($name)
{
    static $config = [];
    if (empty($config)) {
        foreach (Db::name('SystemConfig')->select() as $vo) {
            $config[$vo['name']] = $vo['value'];
        }
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * array_column 函数兼容
 */
if (!function_exists("array_column")) {

    function array_column(array &$rows, $column_key, $index_key = null)
    {
        $data = [];
        foreach ($rows as $row) {
            if (empty($index_key)) {
                $data[] = $row[$column_key];
            } else {
                $data[$row[$index_key]] = $row[$column_key];
            }
        }
        return $data;
    }

}


/***发送邮件
 * @param $to 收件人
 * @param $title 标题
 * @param $content 内容
 * @return bool 是否成功
 */


function sendEmail($to, $title, $content)
{

    Load::import('PHPMailer.PHPMailerAutoload');
    $mail = new \PHPMailer;
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.exmail.qq.com';                   // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'speedup@yangyongan.com';                 // SMTP username
    $mail->Password = 'upSpeed123';                        // SMTP password
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                    // TCP port to connect to

    $mail->setFrom('speedup@yangyongan.com', 'speedup开发者');
    $mail->addAddress($to);


    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = $title;
    $mail->Body = $content;
    $mail->AltBody = 'utf-8';

    if (!$mail->send()) {
        //echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
        return false;
    } else {
        return true;
    }
}

function uid()
{
    return session('user')['id'];
}


function isShiper()
{
    if (uid()) {
        $auth = db('system_user')->where("id", uid())->value('authorize');
        $auth = explode(',', $auth);
        if (in_array("119", $auth)) {
            return true;
        }
    }

    return false;
}


function isMaster()
{
    if (uid()) {
        $master = db('shop')->where('Master', uid())->find();
        if ($master) {
            return $master['Id'];
        }
    }

    return false;


}


/***
 * @param $msg 消息内容
 * @param $room 聊天室ID 多个用逗号分隔
 * @param int $from
 * @return \think\response\Json
 */

function roomMsg($msg, $room = 'web', $from = -1)
{
    $RongCloud = new Api\RongCloud(config('Rong.appKey'), config('Rong.appSecret'));

    $result = $RongCloud->message()->publishChatroom($from, [$room], 'RC:TxtMsg', json_encode($msg));
    return json_decode($result);
}

function publishPrivate($to, $msg, $from = -1)
{

    $RongCloud = new Api\RongCloud(config('Rong.appKey'), config('Rong.appSecret'));

    $result = $RongCloud->message()->publishPrivate($from, $to, 'RC:TxtMsg', json_encode($msg), 'thisisapush', '{\"pushData\":\"hello\"}', '4', '0', '0', '0', '0');
    return json_decode($result);
}


function newShip()
{
    return db('order')->where('Status', 3)->count();
}

function newMaster()
{
    return db('order')->where(['Status' => 1, "ShopId" => isMaster()])->count();
}